package com.dream.myqiyi.ui;

import java.util.ArrayList;
import java.util.List;

import com.dream.myqiyi.R;
import com.dream.myqiyi.dao.NotebookModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.widget.MyListView;
import com.dream.myqiyi.widget.MyListView.OnRefreshListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class NotebookListActivity extends Activity {
	//private View loadMoreView;
	//private Button loadmore_btn;

	private boolean isEditable = false;
	
	private NotebookListAdapter adapter;		// 数据适配器
	private List<NotebookModel> listNewNotes;
	private ArrayList<String> selectData = new ArrayList<String>();

	// Title
	private ImageView mMenu = null;
	private TextView mTitle = null;
	private TextView mNotebookCount = null;
	// body
	private MyListView mDisplay = null;
    private int pageSize=10;					//分页加载的数据的数量
    //menu
	private RelativeLayout mViewBottom = null;	
	private LinearLayout mEditBottom = null;
	private PopMenu popMenuNoteMore;

	private static final int DIALOG_LOAD = 0;
	private static final int DIALOG_DELETE = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_tab_notebooks);

		initUI();
	}
	
	@Override 
	protected void onResume() {  
		super.onResume(); 

		doUpdate(); 
	} 

	private void initUI() {		
		// top
		mMenu = (ImageView) findViewById(R.id.title_menu);
		mMenu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//OpenDesktoop();
				Intent intent = new Intent(NotebookListActivity.this, MainActivity.class);
				startActivity(intent);

			}
		});
		mTitle = (TextView) findViewById(R.id.notes_title_tv);
		mTitle.setText("笔记本");
		mNotebookCount = (TextView) findViewById(R.id.notes_count_tv);

		// mid
		updateLayoutModel();
		
		// bottom
		updateBottomLayout();
	}

	private void updateBottomLayout() {
		if (mViewBottom == null) {
			mViewBottom = (RelativeLayout)findViewById(R.id.bottom_view_layout);
			findViewById(R.id.menu_new_ib).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 切换到NotebookViewActivity
					Intent intent = new Intent(NotebookListActivity.this, NotebookViewActivity.class);
					startActivity(intent);
				}
			});
		
			findViewById(R.id.menu_search_ib).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 切换到NotebookViewActivity
					Intent intent = new Intent(NotebookListActivity.this, NotebookSearchActivity.class);
					startActivity(intent);
				}
			});
	
			findViewById(R.id.menu_more_ib).setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View v) {
					popMenuNoteMore.showAtLocation(v, Gravity.BOTTOM, 0, 90);
				}
			});	
	
			popMenuNoteMore = new PopMenu(NotebookListActivity.this);
			popMenuNoteMore.addItems(new String[] { "删除笔记本" });
			popMenuNoteMore.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					switch (position) {
					case 0:
						isEditable = true;
						// 更新列表模式
						updateAdapter();
						// 更新底部菜单
						updateBottomLayout();

						break;
					}
					popMenuNoteMore.dismiss();
				}
			});
		}

		if (mEditBottom == null) {
			mEditBottom = (LinearLayout)findViewById(R.id.bottom_edit_layout);
			this.findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					new AlertDialog.Builder(NotebookListActivity.this)
						.setTitle("提示")
						.setMessage("确认删除？")
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
							public void onClick(DialogInterface dialog, int which) {
					 		}
						})  
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
							public void onClick(DialogInterface dialog, int whichButton) { 
								NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
								if (noteSrv != null) {
									for (String nbGuid : selectData) {
										if (noteSrv.getNotebookNoteCount(nbGuid) != 0) {
											new AlertDialog.Builder(NotebookListActivity.this)    
											                .setTitle("警告")  
											                .setMessage("所选笔记本中包含笔记，请先清空笔记再删除记事本")  
											                .setPositiveButton("确定", null)  
											                .show();  
											return ;
										}
									}
								}

								new DelNotebooksTask().execute("");
							}  
						})
						.show();  
				}
			});
			this.findViewById(R.id.selectall).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<adapter.getCount();i++){
						adapter.getItem(i).b = true;
					}
					updateAdapter();
				}
				
			});
			this.findViewById(R.id.inverseselect).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<adapter.getCount();i++){
						Item item = adapter.getItem(i);
						item.b = !item.b;//取反
					}
					updateAdapter();
				}
				
			});
			this.findViewById(R.id.cancel).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<adapter.getCount();i++){
						Item item = adapter.getItem(i);
						item.b = !item.b;//取反
					}
					
					isEditable = false;
					// 更新列表模式
					updateAdapter();
					// 更新底部菜单
					updateBottomLayout();
				}
			});
		}
		
		if (isEditable) {
			mEditBottom.setVisibility(View.VISIBLE);
			mViewBottom.setVisibility(View.GONE);
		} else {
			mEditBottom.setVisibility(View.GONE);
			mViewBottom.setVisibility(View.VISIBLE);
		}
	}
	
	private void updateLayoutModel() {        	
        if (mDisplay == null) {
        	mDisplay = (MyListView) findViewById(R.id.lv_all_notes);
        	
            //添加"加载更多"一定要在设置Adapter之前
    		adapter = new NotebookListAdapter(NotebookListActivity.this, R.layout.list_child_item_notebook);
    		mDisplay.setAdapter(adapter);
    		mDisplay.setOnRefreshListener(new OnRefreshListener() {
        		public void onRefresh() {
        			new GetNotebooksTask().execute("");
        		}

				@Override
				public void onLoadMore() {
					// TODO Auto-generated method stub
				}
        	});

    		mDisplay.setOnItemClickListener(new OnItemClickListener() {
    			@Override
    			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    				if (isEditable) {
    					Item item = adapter.getItem(position-1);
    					item.b = !item.b;//取反
    					updateAdapter();    					
    				} else {
	    				// 从适配器中获取当前点击项的内容
	    				NotebookModel notebook = (NotebookModel) adapter.getItem(position-1).notebook;
	    				// 设置当前notebook
	    				NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
	    				nbSrv.setCurrNotebook(notebook);
	
	    				Bundle bundle = new Bundle();
	    				bundle.putInt("note_type", NoteListActivity.NOTEBOOK_TYPE);
	    				bundle.putString("guid", notebook.getGuid());
	    				bundle.putString("name", notebook.getName());
	    				Intent intent = new Intent(NotebookListActivity.this, NoteListActivity.class);
	    				intent.putExtras(bundle);
	
	    				startActivity(intent);
    				}
    			}
    		});
        }  
	}
	        
        
	//刷新适配器
	public void updateAdapter() {

		if (isEditable) {
			int size = adapter.getCount();
			selectData.clear();
			for(int i=0;i<size;i++){
				if(adapter.getItem(i).b) {
					//count++;
					selectData.add(adapter.getItem(i).notebook.getGuid());
				} else {
					selectData.remove(adapter.getItem(i).notebook.getGuid());
				}
			}			
			//tv.setText("已选中 "+data.size()+" 项");
		} else {
			adapter.clear();
			for (int i=0; i<listNewNotes.size(); ++i) {
				adapter.add(new Item(listNewNotes.get(i), false));
			}
		}
		adapter.notifyDataSetChanged();
	}


	protected void doUpdate() {
		new GetNotebooksTask().execute("");
	}

	private class GetNotebooksTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {		 
			// 获取数据
			loadData(0,pageSize);
			return "";
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			if (listNewNotes.size()==0){
				//emptytextView.setVisibility(View.VISIBLE);
			}
			else{
	            //通知适配器，发现改变操作
				updateAdapter();
			}
			
			mDisplay.onRefreshComplete();
			
			mNotebookCount.setText(Integer.toString(adapter.getCount()));
		}
	}
	
	private class DelNotebooksTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {
			NotebookService nvSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
			if (nvSrv != null) {
				for (String nbGuid : selectData) {
					nvSrv.deleteNotebook(nbGuid);
				}
				loadData(0,pageSize);
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_DELETE);
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			removeDialog(DIALOG_DELETE);
            //通知适配器，发现改变操作
			
			if (isEditable)
			{
				adapter.clear();
				for (int i=0; i<listNewNotes.size(); ++i) {
					adapter.add(new Item(listNewNotes.get(i), selectData.contains(listNewNotes.get(i).getGuid())));
				}
			}

			updateAdapter();
			
			mNotebookCount.setText(Integer.toString(adapter.getCount()));
		}
	}

	// 弹出"查看"对话框
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOAD: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("正在加载...请稍候");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		case DIALOG_DELETE: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("正在删除...请稍候");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
			
		}
		return null;
	}


	private void loadData(int pageStart,int pageSize) {
		NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		if (nbSrv != null) {
			listNewNotes = nbSrv.getAllNotebook();
		}

		// 目前每次都是全部数据
	}

	private class NotebookListAdapter extends ArrayAdapter<Item>{
		private int layoutId;

		class NotebookViewHolder {
			public CheckBox note_cb = null;
			public TextView  notebookNameTv = null;
			public TextView  noteCountTv = null;
		}

		public NotebookListAdapter(Activity a, int layout) {
			super(a, layout, new ArrayList<Item>());
			layoutId = layout;
		}
		
		@Override
		public View getView(int position, View view, ViewGroup parent) {
			NotebookViewHolder holder;
			if(view == null || (holder=(NotebookViewHolder)view.getTag()) == null){
				holder = new NotebookViewHolder();
				view = getLayoutInflater().inflate(layoutId, null);
				holder.note_cb = (CheckBox) view.findViewById(R.id.item_cb);
				holder.notebookNameTv = (TextView) view.findViewById(R.id.notebook_name_tv);
				holder.noteCountTv = (TextView) view.findViewById(R.id.note_count_tv);
				view.setTag(holder);
			}
			if (isEditable) {
				holder.note_cb.setVisibility(View.VISIBLE);
				holder.note_cb.setChecked(getItem(position).b);
			} else {
				holder.note_cb.setVisibility(View.GONE);
			}

			holder.notebookNameTv.setText(getItem(position).notebook.getName());
			NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
			holder.noteCountTv.setText(Integer.toString(noteSrv.getNotebookActiveNoteCount(getItem(position).notebook.getGuid())));

			return view;
		}
	}
	
	class Item{
		public NotebookModel notebook;
		public boolean b = false;
		public Item(NotebookModel notebook, boolean b){
			this.notebook = notebook;
			this.b = b;
		}
	}

}
